import { Request, Response, NextFunction } from 'express';
import { createError } from './errorHandler';

export const validateEmail = (email: string): boolean => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
};

export const validatePassword = (password: string): boolean => {
  return password.length >= 6;
};

export const validateUsername = (username: string): boolean => {
  return username.length >= 3 && username.length <= 20;
};

export const validateRegisterInput = (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  const { username, email, password } = req.body;

  if (!username || !email || !password) {
    return next(createError('Username, email, and password are required', 400));
  }

  if (!validateUsername(username)) {
    return next(createError('Username must be between 3 and 20 characters', 400));
  }

  if (!validateEmail(email)) {
    return next(createError('Please provide a valid email address', 400));
  }

  if (!validatePassword(password)) {
    return next(createError('Password must be at least 6 characters long', 400));
  }

  next();
};

export const validateLoginInput = (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  const { email, password } = req.body;

  if (!email || !password) {
    return next(createError('Email and password are required', 400));
  }

  if (!validateEmail(email)) {
    return next(createError('Please provide a valid email address', 400));
  }

  next();
};

export const validateAlgorithmInput = (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  const { title, description, difficulty } = req.body;

  if (!title || !description || !difficulty) {
    return next(createError('Title, description, and difficulty are required', 400));
  }

  if (title.length < 1 || title.length > 255) {
    return next(createError('Title must be between 1 and 255 characters', 400));
  }

  if (!['easy', 'medium', 'hard'].includes(difficulty)) {
    return next(createError('Difficulty must be easy, medium, or hard', 400));
  }

  next();
};

export const validateTodoInput = (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  const { title, listId } = req.body;

  if (!title) {
    return next(createError('Title is required', 400));
  }

  if (title.length < 1 || title.length > 255) {
    return next(createError('Title must be between 1 and 255 characters', 400));
  }

  if (listId && typeof listId !== 'number') {
    return next(createError('List ID must be a number', 400));
  }

  next();
};

export const validateTodoListInput = (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  const { name } = req.body;

  if (!name) {
    return next(createError('Name is required', 400));
  }

  if (name.length < 1 || name.length > 255) {
    return next(createError('Name must be between 1 and 255 characters', 400));
  }

  next();
};